

var GRID_SIZE = 40; // 单元格的大小
var HORIZONTAL_SIZE =15; // 水平方向格子的数量
var VERICAL_SIZE = 12;  //垂直方向格子德数量
var cvs = document.getElementById('cvs');
var ctx = cvs.getContext('2d');
/*
* 表示一个棋盘 一个格子代表一个对象
* state [boolean] 是否能放旗子
* type [boolean] 是白棋还是黑棋
* */
var checkerboard = [];   // 旗子是否能落下
var whiteTrun = true;

cvs.width = GRID_SIZE * HORIZONTAL_SIZE;
cvs.height = GRID_SIZE * VERICAL_SIZE;

document.getElementById('reStart').onclick=function () {
    document.getElementById('tips').innerText = '';
    init()
};
init();
// 初始化
function init() {
    for (var i=-5;i<HORIZONTAL_SIZE+5;i++){
        checkerboard[i]=[];
        for (var j=-5;j<VERICAL_SIZE+5;j++){
            checkerboard[i][j]={
                state:0,
                type:true
            }
        }
    }
    drawCheckrboard();
    cvs.onclick = putChecs;
}

// 画棋盘
function drawCheckrboard() {
    for(var i=0;i<HORIZONTAL_SIZE;i++){
        for (var j = 0;j<VERICAL_SIZE;j++) {
            ctx.beginPath();
            ctx.strokeStyle='#000';
            ctx.fillStyle = '#ffc0cb';
            ctx.fillRect(i*GRID_SIZE,j*GRID_SIZE,GRID_SIZE,GRID_SIZE);
            ctx.strokeRect(i*GRID_SIZE,j*GRID_SIZE,GRID_SIZE,GRID_SIZE);
            ctx.closePath()

        }
    }
}
//画旗子
function drawArc(x,y){
    ctx.beginPath();
    ctx.arc(x * GRID_SIZE + GRID_SIZE / 2,y * GRID_SIZE + GRID_SIZE / 2,(GRID_SIZE / 2)*0.8,0,2 * Math.PI);
    ctx.fillStyle=(whiteTrun===true?'#fff':'#000');
    ctx.fill();
    ctx.closePath();
    checkerboard[x][y].state = 1;
    checkerboard[x][y].type = whiteTrun;
    whiteTrun = !whiteTrun
}


// 放置旗子
function putChecs(e) {
  var x = e.pageX-cvs.offsetLeft;
  var y = e.pageY-cvs.offsetTop;
  x= parseInt(x/GRID_SIZE);
  y= parseInt(y/GRID_SIZE);
  if(checkerboard[x][y].state) return;
  drawArc(x,y);
  document.getElementById('tips').innerText=(whiteTrun===true?'现在轮到白棋落子了':'现在轮到黑棋落子了');
  gameover(x,y)
}
// 判断游戏是否结束
function gameover(x,y) {
    // 从左上角到右下角是否满足条件
   if(!checkAllDirectionClass(x,y)) return;
     var chess = whiteTrun?'黑棋':'白棋';
     document.getElementById('tips').innerText=chess + '胜'

   cvs.onclick = null
}

//判断五指棋是否满足条件
function checkAllDirectionClass(x,y) {
   if(checkOnlineChess(x-5,y-5,1,1,checkerboard[x][y].type)) return true;
   if(checkOnlineChess(x,y-5,0,1,checkerboard[x][y].type)) return true;
   if(checkOnlineChess(x+5,y-5,-1,1,checkerboard[x][y].type)) return true;
   if(checkOnlineChess(x-5,y,1,0,checkerboard[x][y].type)) return true;
   return false
}


//判断一个方向上是否满足
function checkOnlineChess(tpx,tpy,xPlus,yPlus,type) {
    var count = 0;
    for(var i =0;i<10;i++){
        if(checkerboard[tpx][tpy].type === type && checkerboard[tpx][tpy].state !==0 ){
            count ++;
            if(count >= 5) return true;
        }else{
            count = 0;
        }
        tpx += xPlus;
        tpy += yPlus
    }
}
